package com.taikang.hmp.hservice.doctor.pm25.service.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import net.sf.json.JSONObject;

import com.taikang.hmp.frame.common.redis.RedisRemote;
import com.taikang.hmp.frame.common.service.impl.BaseServiceImpl;
import com.taikang.hmp.frame.common.spring.SpringBeanLoader;
import com.taikang.hmp.hservice.doctor.pm25.service.IWeatherInfoService;

public class WeatherInfoServiceImpl extends BaseServiceImpl implements IWeatherInfoService{
	private String key = "QN2ZD5D6JN";
	
	private RedisRemote redisClient= null;
	
	public WeatherInfoServiceImpl(){
		 redisClient = SpringBeanLoader.getSpringBean("doctorRedisData");
	}
	/**
	 * 获取pm2.5
	 */
	public JSONObject getAirNowInfo(String cityName) {
		JSONObject airNowObject = this.getAirNowInfoFromRedis(cityName);
		if (airNowObject != null) {
			return airNowObject;
		}
		
		airNowObject = this.loadAirNowInfo(cityName);
		if (airNowObject != null) {
			this.saveAirNowInfoToRedis(cityName, airNowObject);
		}
		
		return airNowObject;
	}
	/**
	 * 从redis中获取参数
	 * @param cityName
	 * @return
	 */
	private JSONObject getAirNowInfoFromRedis(String cityName) {
		String key = "air-now:" + cityName;
		String value = (String)this.redisClient.get(key);
		if (value != null) {
			return JSONObject.fromObject(value);
		} else {
			return null;
		}
	}
	/**
	 * redis保存获取的参数
	 * @param cityName
	 * @param airNowObject
	 */
	private void saveAirNowInfoToRedis(String cityName, JSONObject airNowObject) {
		String key = "air-now:" + cityName;
		this.redisClient.set(key, airNowObject.toString());
	}
	
	private JSONObject loadAirNowInfo(String cityName){
		String airNowUrl = "http://api.thinkpage.cn/v3/air/now.json?key=" + this.key + "&location=" + cityName + "&language=zh-Hans&scope=city";
		String result = "";
		BufferedReader reader = null;
		try {
		    URL realurl = new URL(airNowUrl);
		    URLConnection connection = realurl.openConnection();
		    connection.connect();
		    reader = new BufferedReader(new InputStreamReader(
		       connection.getInputStream(), "UTF-8"));
		    String line;
		    while ((line = reader.readLine()) != null) {
		       result += line;
		    }
		} catch (IOException e) {
		    e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		    }
		}
		
		JSONObject airNowObject = JSONObject.fromObject(result);
		
		return airNowObject;
	}
}
